<?php

namespace Modules\Node\Controllers;

use Core\Mvc\Controller;
use Modules\Node\Entity\Node;
use Modules\Core\Models\Meta;
use Modules\Node\Library\NodePagination;
use MongoDB\BSON\ObjectID;
use Core\Paginator\Adapter\Collection as CollectionPaginator;

class IndexController extends Controller
{

    public function indexAction()
    {
        $id = self::$variables['router_params']['id'];
        $contentModel = self::$variables['router_params']['contentModel'];
        if (isset(self::$variables['router_params']['page'])) {
            $page = self::$variables['router_params']['page'];
        }
        $data = $this->entityManager->get('node', [
            'conditions' => [
                '_id' => new ObjectID($id)
            ]
        ]);
        if (!$data || $data->created > time() || $contentModel != $data->contentModel) {
            return $this->notFount();
        }

        $nodeContentModelList = $this->entityManager->contentModel('node');

        $nodePagination = [];
        $nodeConfig = $this->config->get('m.node.config');
        if ($nodeConfig['pagination'] != 0 && array_search($data->contentModel, $nodeConfig['open_pagination']) && isset($data->body)) {
            if (isset($page) && $page < 2) {
                return $this->notFount();
            }
            $nodePaginationOb = new NodePagination($data->body);
            $nodePagination = $nodePaginationOb->cut_str();
        }
        if (!isset($page)) {
            $page = 1;
        }

        if (isset($nodeConfig['browse']) && $nodeConfig['browse']) {
            $data->socialize('browse');
        }


        self::$variables['title'] = $data->getTitle();
        self::$variables += array(
            '#templates' => array(
                'pageNode',
                'pageNode-' . $data->contentModel,
                'pageNode-' . $id,
            ),
            'page' => $page,
            'contentModelList' => $nodeContentModelList,
            'contentModelInfo' => $nodeContentModelList[$data->contentModel],
            'contentModel' => $data->contentModel,
            'nodePagination' => $nodePagination,
            'currentPageIndex' => $page - 1,
            'data' => $data,
        );
    }

    public function loveAction($id)
    {
        if (!$this->request->isAjax()) {
            return $this->notFount();
        }
        self::$variables['#templates'] = 'json';
        $node = $this->entityManager->get('node', [
            'conditions' => [
                '_id' => new ObjectID($id)
            ]
        ]);
        //$node = Node::findById($id);
        if ($node && $node instanceof Node) {
            if ($node->socialize('love')) {
                $data = [
                    'state' => true,
                    'number' => $node->love,
                    'notice' => '宝宝成功赞了一下',
                ];
            } else {
                $error = '';
                foreach ($node->getMessages() as $message) {
                    $error .= $message . "\n";
                }

                $data = [
                    'state' => false,
                    'notice' => $error . '数据保存失败，稍后试试吧',
                ];
            }
        } else {
            $data = [
                'state' => false,
                'notice' => '文章不在了',
            ];
        }
        self::$variables['data'] = $data;
    }

    public function termAction($contentModel, $id, $page)
    {
        $nodeConfig = $this->config->get('m.node.config');
        $term = $this->entityManager->get('term', [
            'conditions' => [
                '_id' => new ObjectID($id)
            ]
        ]);
        if (!$term || $contentModel != $term->contentModel) {
            return $this->notFount();
        }

        $nodeFields = $this->entityManager->field('node');
        $termFieldList = [];
        foreach (formFieldInit($nodeFields) as $fieldName => $field) {
            if (isset($field['term'])) {
                $termFieldList[$fieldName] = $fieldName;
            }
        }

        $conditions = [];
        foreach ($termFieldList as $field) {
            $conditions[$field] = [
                '$in' => [$id]
            ];
        }

        $query = [
            'conditions' => $conditions,
            'sort' => [
                'changed' => -1
            ],
            'limit' => $nodeConfig['term_number'],
            'skip' => $nodeConfig['term_number'] * ($page - 1)
        ];
        $data = $this->entityManager->find('node', $query);
        $dataPagination = new CollectionPaginator([
            'data' => $data,
            'query' => $query,
            'page' => $page,
            'collection' => '\Modules\Node\Entity\Node'
        ]);
        self::$variables['title'] = $term->name;
        self::$variables['description'] = $term->description;
        self::$variables['keywords'] = (isset($term->keywords) && $term->keywords) ? $term->keywords : $term->name;
        self::$variables += array(
            '#templates' => array(
                'pageNodeTerm',
                'pageNodeTerm-' . $term->contentModel,
                'pageNodeTerm-' . $id,
            ),
            'contentModel' => $term->contentModel,
            'id' => $id,
            'page' => $page,
            'term' => $term,
            'data' => $dataPagination->getPaginate(),
        );
    }

    public function typeAction($contentModel, $page)
    {
        $nodeConfig = $this->config->get('m.node.config');
        $contentModelList = $this->entityManager->contentModel('node');
        if (!isset($contentModelList[$contentModel])) {
            return $this->notFount();
        }
        $query = [
            'conditions' => [
                'contentModel' => $contentModel
            ],
            'sort' => [
                'changed' => -1
            ],
            'limit' => $nodeConfig['number'],
            'skip' => $nodeConfig['number'] * ($page - 1)
        ];
        $data = $this->entityManager->find('node', $query);
        $dataPagination = new CollectionPaginator([
            'data' => $data,
            'query' => $query,
            'page' => $page,
            'collection' => '\Modules\Node\Entity\Node'
        ]);
        self::$variables['title'] = $contentModelList[$contentModel]['name'];
        self::$variables['description'] = $contentModelList[$contentModel]['description'];
        self::$variables += array(
            '#templates' => array(
                'pageNodeType',
                'pageNodeType-' . $contentModel,
            ),
            'data' => $dataPagination->getPaginate(),
            'nodeContentModelInfo' => $contentModelList[$contentModel],
            'contentModel' => $contentModel,
            'page' => $page,
        );
    }
}
